//
//  HomeViewController.m
//  BProject
//
//  Created by 久远的回忆 on 15/8/11.
//  Copyright (c) 2015年 久远的回忆. All rights reserved.
//

#import "HomeViewController.h"
#import "PKRequestManager.h"
#import "HomeModel.h"
#import "HomeCell.h"
#import "TopBannersView.h"
#import "LORefresh.h"
#import "HomeDetilViewController.h"
typedef NS_ENUM(NSInteger, RefreshType){
    LORefreshNew,
    LORefreshMore
};
@interface HomeViewController ()
@property (nonatomic,assign)RefreshType type;
@property (nonatomic, strong) NSMutableArray *bannerArr;   // 轮播图的数据源
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) NSString *last_time; /**<用来存储下一次请求的参数*/
@end

@implementation HomeViewController

static NSString * const reuseIdentifier = @"Cell";


- (NSMutableArray *)dataSource
{
    if (_dataSource == nil) {
        self.dataSource = [[NSMutableArray alloc]initWithCapacity:0];;
    }
    return _dataSource;
}


/**
 *  数据解析
 */
- (void)parserData
{
    
    NSString *urlStr = nil;
    
    if (_last_time == nil) {
        urlStr = @"http://app.qdaily.com/app/homes/index/0.json";
    }else{
        urlStr = [NSString stringWithFormat:@"http://app.qdaily.com/app/homes/index/%@.json",_last_time];
    }
    
    [PKRequestManager manager:GET requestWith:urlStr parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        
        if (_type == LORefreshNew) {
            [_dataSource removeAllObjects];
        }
        // 存储下一次解析需求的阐述
        _last_time = nil;
        _last_time = dic[@"response"][@"feeds"][@"last_time"];
        
        
        // 存储顶部轮播图数据
        NSArray *banners = dic[@"response"][@"banners"][@"list"];
        _bannerArr = [NSMutableArray arrayWithCapacity:0];
        for (NSDictionary *dict in banners) {
            HomeModel *model = [[HomeModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [_bannerArr addObject:model];
        }
        
        
        // 解析下面的列表数据
        NSArray *feeds = dic[@"response"][@"feeds"][@"list"];
        for (NSDictionary *dict in feeds) {
            HomeModel *model = [[HomeModel alloc]init];
            [model setValuesForKeysWithDictionary:dict];
            [self.dataSource addObject:model];
        }
        [self.collectionView.defaultFooter endRefreshing];
        [self.collectionView.defaultHeader endRefreshing];
        [self.collectionView reloadData];
        
    } error:^(NSError *error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
//    layout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 180);
    [self.collectionView setCollectionViewLayout:layout];
    [self parserData];
    
    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = NO;
    //上拉加载
    __weak HomeViewController * controller = self;
    [self.collectionView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        _last_time = @"0";
        _type = LORefreshNew;
        [controller parserData];
    }];
    
    [self.collectionView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        _type = LORefreshMore;
        [controller parserData];
    }];
    // Register cell classes
    [self.collectionView registerClass:[HomeCell class] forCellWithReuseIdentifier:reuseIdentifier];
    [self.collectionView registerClass:[TopBannersView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(SCREEN_WIDTH, 200);
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return _dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    HomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    cell.model = _dataSource[indexPath.row];
    //set offset accordingly
    CGFloat yOffset = ((self.collectionView.contentOffset.y - cell.frame.origin.y) / IMAGE_HEIGHT) * IMAGE_OFFSET_SPEED;
    cell.imageOffset = CGPointMake(0.0f, yOffset);
    
    return cell;
}



#pragma mark - headerView

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
       if (kind == UICollectionElementKindSectionHeader) {
        
        TopBannersView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        header.modelArr = _bannerArr;
        return header;
    }
    
    return nil;
}




- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    HomeModel *model = _dataSource[indexPath.row];
    
    HomeDetilViewController *detailVC = [[HomeDetilViewController alloc]init];
    detailVC.model = model;
    [self.navigationController pushViewController:detailVC animated:YES];
}



#pragma mark - UIScrollViewdelegate methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    for(MJCollectionViewCell *view in self.collectionView.visibleCells) {
        CGFloat yOffset = ((self.collectionView.contentOffset.y - view.frame.origin.y) / IMAGE_HEIGHT) * IMAGE_OFFSET_SPEED;
        view.imageOffset = CGPointMake(0.0f, yOffset);
    }
}

@end
